package com.sky.service.admin.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.dto.CategoryDTO;
import com.sky.entity.Category;
import com.sky.mapper.admin.CategoryMapper;
import com.sky.service.admin.CategoryService;
import com.sky.utils.ChangeType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
@Transactional
@RequiredArgsConstructor
/**
 * 想起来可以直接super直接调用mybatis-plus的所有原curd代码，
 * 无需直接再实现
 */
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper,Category> implements CategoryService {
    private final CategoryMapper categoryMapper;
    @Override
    @Cacheable(value = "category",key = "'list:' + ('all')")
    public List<Category> getByType(Integer type) {
        log.info("查询分类：{}",type);
        List<Category> list = categoryMapper.getByType(type);
        return list;
    }

    @Override
    @CacheEvict(value = "category",key = "'list:' + ('all')")
    public void deleteById(Integer id) {
        categoryMapper.delete(new QueryWrapper<Category>().eq("id",id));
    }

    @Override
    @CachePut(value = "category",key = "'list:' + ('all')")
    public void addByObject(CategoryDTO  categoryDTO) {
        Category categoryType = new Category();
        Category category = ChangeType.change(categoryDTO, categoryType);
        categoryMapper.insert(category);
    }

    @Override
    public IPage<Category> myPage(String name, Integer page, Integer pageSize, Integer type) {
        Page<Category> categoryPage = new Page<>();
        categoryPage.setSize(pageSize);
        categoryPage.setCurrent(page);

        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(type != null, "type", type)
                .like(name != null, "name", name);
        return categoryMapper.selectPage(categoryPage, queryWrapper);
    }

    @Override
    @CacheEvict(value = "category",key = "'list:' + ('all')")
    public void myUpdateById(Integer id, Integer status) {
        Category category = categoryMapper.selectById(id);
        category.setStatus(status);
        categoryMapper.updateById(category);
    }

}
